//
//  GRUserBasisInfo.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/12.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRUserBasisInfo.h"

NSString *const KBasisUserInfoKey = @"BasisUserInfoKey";

@interface GRUserBasisInfo ()

@property (nonatomic, strong) GRBasisKeyModel *basisModel;

@end

@implementation GRUserBasisInfo

+ (instancetype)shareBasis {
    static GRUserBasisInfo *user = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [[GRUserBasisInfo alloc] init];
    });
    
    return user;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.basisModel = [self getBasisInfoFromLocal];
    }
    return self;
}

- (GRBasisKeyModel *)getBasisInfoFromLocal {
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:KBasisUserInfoKey];
    
    if (data) {
        GRBasisKeyModel *basisModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        return basisModel;
    }
    
    return nil;
}

+(CGFloat)recommendUser{
    return [[GRUserBasisInfo shareBasis].basisModel recommendUser];
    
}

+(CGFloat)recommendStore{
    return [[GRUserBasisInfo shareBasis].basisModel recommendStore];
}

- (void)saveBasisKey:(GRBasisKeyModel *)basisKey {
    if (basisKey) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:basisKey];
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:KBasisUserInfoKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        self.basisModel = basisKey;
    }
}

- (void)doLogin {
    [self LogOut:YES];
}


- (void)LoginOut {
    [self LogOut:NO];
}


/**
 登录 或 退出

 @param status <#status description#>
 */
- (void)LogOut:(BOOL)status {
    GRBasisKeyModel *basisModel = [[GRUserBasisInfo shareBasis] basisModel];
    basisModel.isLogin = status;
    if (!status) {
        basisModel.token = @"";
    }
    [self saveBasisKey:basisModel];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LoginToExitNotificationName object:self userInfo:@{@"Login":@(status)}];
}

+ (GRBasisKeyModel *)UserBasis {
    return [GRUserBasisInfo shareBasis].basisModel;
}

+ (NSString *)BasisID {
    return [[GRUserBasisInfo shareBasis].basisModel profileId];
}

+ (NSString *)Token {
    return [[GRUserBasisInfo shareBasis].basisModel token];
}

+ (NSString *)UploadToken {
    return [[GRUserBasisInfo shareBasis].basisModel uploadToken];
}

+ (BOOL)isLogin {
    return [[GRUserBasisInfo shareBasis].basisModel isLogin];
}

+(BOOL)isAuth{
    return [[GRUserBasisInfo shareBasis].basisModel appraisal];
    
}

@end
